package com.example.blog.dao;

import java.sql.*;

import com.example.blog.pojo.User;
import com.example.blog.utils.JDBCUtils;

public class UserDAO 
{
	/**
	 * 
	 * @param username
	 * @return						1 表示找到   0 表示没找到
	 * @throws SQLException
	 */
	public int findByName(String username)throws SQLException
	{
		// 1. 获取连接
		Connection conn = JDBCUtils.getConnection();

		// 2. 创建Statment
		String sql = "select * from user where username=?";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, username);

		// 3. 执行层语句
		ResultSet rs = stmt.executeQuery();
		User u = null;
		int result = 0;
		if(rs.next())
		{
			result=1;
		}

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);
		
		return result;
	}

	public int insert(User user) throws SQLException {
		// 1. 获取连接
		Connection conn = JDBCUtils.getConnection();

		// 2. 创建Statment
		String sql = "insert into user values (null,?,?)";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, user.getUsername());
		stmt.setString(2, user.getPassword());

		// 3. 执行层语句
		int result = stmt.executeUpdate();

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);

		return result;

	}

	public User findBy(String username, String password) throws SQLException {
		// 1. 获取连接
		Connection conn = JDBCUtils.getConnection();

		// 2. 创建Statment
		String sql = "select * from user where username=? and password=?";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, username);
		stmt.setString(2, password);

		// 3. 执行层语句
		ResultSet rs = stmt.executeQuery();
		User u = null;
		if(rs.next())
		{
			int id = rs.getInt(1);// 通过列号获取
			u = new User();
			u.setId(id);
			u.setUsername(username);
			u.setPassword(password);
		}

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);

		return u;

	}
}
